<script setup>
import { ElMessage } from 'element-plus';
import { useProductApi } from '/@/api/product';
import { isEmpty } from '/@/utils';

const { getDimensionList, addDimension } = useProductApi();

const props = defineProps({
	attrName: {
		type: String,
	},
});
const emit = defineEmits(['update:attrName']);
const selectedAttrName = computed({
	get() {
		return props.attrName;
	},
	set(attrName) {
		emit('update:attrName', attrName);
	},
});
const options = ref([]);
const loading = ref(false);
//远程搜索
async function remoteMethod(query) {
	try {
		let params = {
			current: 1,
			pageSize: 99,
			status: 1,
			attrName: query === ' ' ? null : query,
		};
		loading.value = true;
		let res = await getDimensionList(params);
		loading.value = false;
		if (res.code !== 200) return;
		options.value = res.data.data;
	} catch (error) {
		loading.value = false;
	}
}
onMounted(() => {
	remoteMethod('');
});
//更改选项时
function change(val) {
	if (isEmpty(val)) return;
	const isSelect = options.value.find(({ attrName }) => attrName === val);
	if (isSelect) return;
	addDimensionItem(val);
}
//创建维度词条
async function addDimensionItem(attrName) {
	loading.value = true;
	let res = await addDimension({
		attrName,
		status: 1,
	});
	loading.value = false;
	if (res.code !== 200) return;
	ElMessage.success('新参数创建成功！');
	options.value.unshift(res.data);
}
</script>
<template>
	<div class="DimensionsSelector">
		<el-select
			v-model="selectedAttrName"
			filterable
			remote
			reserve-keyword
			allow-create
			default-first-option
			placeholder="请输入关键词"
			:remote-method="remoteMethod"
			:loading="loading"
			clearable
			@change="change"
		>
			<el-option v-for="(item, index) in options" :key="index" :label="item.attrName" :value="item.attrName"> </el-option>
		</el-select>
	</div>
</template>
